import requests
import json
from pyecharts.charts import Line
from pyecharts import options as opts
import json
from fastapi import FastAPI
import os
import uvicorn
from starlette.responses import HTMLResponse

def line_html(sn,username,password):
# 登录 URL
    login_url = "https://1weilian.com//user/login"

    # 登录请求头
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection": "keep-alive",
        "Content-Type": "application/json;charset=UTF-8",
        "Origin": "https://1weilian.com",
        "Referer": "https://1weilian.com/",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
        "sec-ch-ua": '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
        "sec-ch-ua-mobile": "?0",
        #"Cookie": "SECKEY_ABVK=CgV1aMZGqTa1/OiPro2c4OC4HnaFlLXyyzIiTOQIzAs=; BMAP_SECKEY=CgV1aMZGqTa1_OiPro2c4AulQ_7eWjyohbU21DShNsMl67ztVPJkdu0w59bavAs2HNzGJM0fjPOtjAFg5PmZhzcExjKoEQ79h0Vomi7naVuDEGtTK-DxQC4hANdT_c6Q8NjDL-MXpUj8Bl-oEqXqUvYs9xA_aCHkeug_iRJlc5mC89vMmOBVg_R7dL0dUAyi",
        "sec-ch-ua-platform": '"Windows"'
    }

    # 登录请求体
    data = {
        "account": username,
        "pwd": password,
        "systemVersion": "PC",
        "loginType": 2
    }

    # 创建 session 对象
    session = requests.Session()

    # 发送 POST 请求
    response = session.post(login_url, headers=headers, data=json.dumps(data))
    #print('response',response)

    # 检查响应状态码
    if response.status_code == 200:
        # 将响应内容转换为 JSON 对象
        response_data = response.json()
        print('response_data',response_data)
        
        # 提取 accessToken
        access_token = response_data.get('data')['accessToken']  # 根据实际的键名来获取 accessToken
        
        if access_token:
            print('获取到 accessToken:', access_token)
        else:
            print('登录成功，但未返回 accessToken')
    else:
        print('登录失败，状态码：', response.status_code)

    ### 访问另一个链接
    url1 = "https://1weilian.com//historical/selectHistoryData"
    ##
    ### 发送 GET 请求
    data1 = {
        "userId": 60284,
        "loginType": 2,
        "accessToken": "e3d75ca3de2844dd9838145f71649a8b",
        "permissions": 2,
        "subUserId": None,
        "sn": sn,
        "deviceName": None,
        "sharedUserId": None,
        "regionalId": None,
        "language": 1,
        "isShare": None,
        "rows": 15,
        "page": 0,
        "startTime": "",
        "endTime": ""
    }
    data1["accessToken"]=access_token

    # 发送 POST 请求
    response = requests.post(url1, headers=headers, data=json.dumps(data1))
    #print(response.text)
    #data_json=response.text
    data_json = json.loads(response.text)
    data = data_json["data"]["dataList"]
    devicename=data[0]["deviceName"]
    print('devicename',devicename)

    # 提取日期、温度和湿度
    dates = [item["date"] for item in data]
    temperatures = [float(item["temperature"]) for item in data]
    humidities = [float(item["humidity"]) for item in data]

    # 创建折线图
    line_chart = Line()
    line_chart.add_xaxis(dates)
    line_chart.add_yaxis("温度", temperatures, is_smooth=True)
    line_chart.add_yaxis("湿度", humidities, is_smooth=True)

    # 设置全局配置
    line_chart.set_global_opts(
        title_opts=opts.TitleOpts(title="温度和湿度随时间变化"),
        tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
        yaxis_opts=opts.AxisOpts(name="值"),
        xaxis_opts=opts.AxisOpts(name="时间",type_="time", boundary_gap=False),
    )

    # 渲染图表到 HTML 文件
    line_chart.render("temperature_humidity_chart.html")
    html=line_chart.render_embed()
    return '<h2>'+devicename+'</h2>'+html

app = FastAPI()
@app.get("/")
def home():
    html=line_html(sn,username,password)
    #print('html',html)
    return HTMLResponse(content=html)
if __name__ == "__main__":

    print('当前程序名称为:',os.path.basename(__file__))
    filename=os.path.basename(__file__).split('.')[0]
    sn="C00340200031"
    username="wjb71111"
    password="*****"
    uvicorn.run(app, host="0.0.0.0",port=8000,log_level="info")
